var OperAct = require('./MajiangOperAct');
var MJLogic           = require('./MJLogic');

cc.Class({
    extends: cc.Component,

    properties: {
        _dir: 0,
        dir: {
            get() { return this._dir; },
            set(n) {
                this._dir = n;
                this.reset(this._num);
            }
        },

        mjprefab: cc.Prefab,
        _mjNodeList: [cc.Node],
        _mjList: [],

        _num: 0,
        num: {
            get() {
                return this._num;
            },
            set(n) {
                this._num = n;
                this.reset(this._num);
            },
        },

        _test: 0,
        getMj: {
            get() {
                return this._test;
            },
            set(n) {
                this._test = n;
                if (this._test == -1) {
                    this.clearNewMj();
                } else {
                    this.getNewMj(this._test);
                }
            },
        },

        _outnum: 0,
        outnum: {
            get() { return this._outnum; },
            set(n) {
                this._outnum = n;
                this.testOutList(this._outnum);
            },
        },

        OperAct: OperAct,
		tingNode: cc.Node,
		mjAtlas: cc.SpriteAtlas,

        _outLineNum: 12,
        _newMj: null,
        _outList: [],
        _operList: [],
        _hunpai: 35,
        hunpai: {
            get() { return this._hunpai; },
            set(n) { this._hunpai = n; },
        }
    },

    onLoad() {
		this._hunpai = 35;
		this._outLineNum = 12;
    },

	setChairCount: function (count) {
		this.chairCount = count;
	},

	clearAllCards: function () {
		this.clearMJ();
		this.clearNewMj();
		this.clearOperMjList();
		this.clearOutMjFlag();
		this.clearAllOutMj();
	},

    setDirPos() {
        if (this._dir == 0) {
            this._beginX = 472; //手持麻将开始的坐标x
            this._beginY = -290; //手持麻将开始的坐标y
            this._intervalX = -87; //手持麻将坐标x 间隔
            this._intervalY = 0; //手持麻将坐标y 间隔
            this._newX = 592; //摸牌麻将坐标x 
            this._newY = -290; //摸牌麻将坐标y

            this._outBeginX = -235; //出牌麻将开始的坐标x
            this._outBeginY = -100; //出牌麻将开始的坐标y
            this._outIntervalX = 40; //出牌麻将 x轴间隔   兼容操作用牌的横轴间隔
            this._outIntervalY = -46; //出牌麻将 y轴间隔   兼容操作用牌的横轴间隔

            this._operationX = -590; //操作麻将（吃碰杠）开始的坐标x
            this._operationY = -297; //操作麻将（吃碰杠）开始的坐标y
            this._operationIntervalX = 20; //操作麻将（吃碰杠）x轴间隔
            this._operationIntervalY = 22; //操作麻将（吃碰杠）y轴间隔
            this._operationIntervalY2 = 0; //操作麻将（吃碰杠）两堆 y轴间隔
			if (this.chairCount == 2) {
				this._outBeginX = -340;
				this._outLineNum = 18;
			}
        } 
		else if (this._dir == 1) {
            this._beginX = 480;
            this._beginY = 200;
            this._intervalX = 0;
            this._intervalY = -26;
            this._newX = 480;
            this._newY = 240;
            this._outBeginX = 300;
            this._outBeginY = -134;
            this._outIntervalX = 49;
            this._outIntervalY = 27;

            this._operationX = 440+40;
            this._operationY = -155-30;
            this._operationIntervalX = 20;
            this._operationIntervalY = 26;
            this._operationIntervalY2 = 11;
        } 
		else if (this._dir == 2) {
            this._beginX = -300;
            this._beginY = 290;
            this._intervalX = 38;
            this._intervalY = 0;
            this._newX = -350;
            this._newY = 290;
            this._outBeginX = 170;
            this._outBeginY = 140;
            this._outIntervalX = -36;
            this._outIntervalY = 42;

            this._operationX = 220;
            this._operationY = 290;
            this._operationIntervalX = -20;
            this._operationIntervalY = 13;
            this._operationIntervalY2 = 0;
			if (this.chairCount == 2) {
				this._outBeginX = 300;
				this._outLineNum = 18;
			}
        } 
		else if (this._dir == 3) {
            this._beginX = -500;
            this._beginY = -130;
            this._intervalX = 0;
            this._intervalY = 26;
            this._newX = -500;
            this._newY = -176;
            this._outBeginX = -320;
            this._outBeginY = 160;
            this._outIntervalX = -49;
            this._outIntervalY = -27;

            this._operationX = -495;
            this._operationY = 220+30;
            this._operationIntervalX = -20;
            this._operationIntervalY = -26;
            this._operationIntervalY2 = 11;
        }
    },

    clearMJ() {
        for (let i = this._mjNodeList.length; i > 0; i--) {
            let mj = this._mjNodeList[i - 1];
            mj.destroy();
        }
        this._mjNodeList = [];
    },

    showShaiPai(shaipai) {
        if (shaipai != null && shaipai != 0) {
            this.ShaiPaiNode.active = true;
            let reslogic = this.ShaiPaiNode.getChildByName('MaJiang').getComponent('MJRes');
            reslogic.majiang = shaipai;
        }
    },

	reset: function (list, qidui) {
        if (typeof (list) == 'number') {
            let num = list;
            list = [];
            for (let i = 0; i < num; i++) {
                list.push(36);
            }
        }
		if (this._dir == 0) {
			this.showTing(list.slice(), qidui);
		}
        this.clearMJ();
        this.setDirPos();

        let hunpailist = [];
        if (this._hunpai != 0) {
            let delhunpai = (plist, k) => {
                for (let i = k; i < plist.length; i++) {
                    let p = plist[i];
                    if (p == this._hunpai) {
                        hunpailist.push(p);
                        plist.splice(i, 1);
                        return delhunpai(plist, i);
                    }
                }
                return plist;
            }
            list = delhunpai(list, 0);
        }
        list.sort((a, b) => { return b - a; });
        if (this._hunpai != 0) {
            for (let i = 0; i < hunpailist.length; i++) {
                list.push(hunpailist[i]);
            }
        }

        let self = this;
        this._mjList = list;
        for (let i = 0; i < list.length; i++) {
            let point = list[i];
            let mj = cc.instantiate(this.mjprefab);
            let reslogic = mj.getComponent('MJRes');
            reslogic.onlyid = i;
            reslogic.dir = this._dir;
            reslogic.isStand = true;
            if (this._dir == 0) {
                reslogic.canSend = true;
				mj.setScale((83+5)/83, (125+7.5)/125);
            }
			else {
				reslogic.isStand = false;
				reslogic.isShow = true; 
			}
            this.setMjPoint(mj, point);

            mj.x = this._beginX + i * this._intervalX;
            mj.y = this._beginY + i * this._intervalY;
            mj.parent = this.node;
            mj.zIndex = (320 - mj.y);
            this._mjNodeList.push(mj);
        }
    },

    setMjPoint(node, n) {
        let reslogic = node.getComponent('MJRes');
        if (n == null) { n = 36; }
        if (this._hunpai == n) {
            reslogic.isHun = true;
        }
        reslogic.majiang = n;
    },

    setMjs(list) {
        if (this._dir != 0) {
            return;
        }
        for (let index = 0; index < list.length; index++) {
            const point = list[index];
            let mjnode = this._mjNodeList[index];
            this.setMjPoint(mjnode, point);
        }
    },

    clearNewMj() {
        if (this._newMj) {
            let index = this._mjNodeList.indexOf(this._newMj);
            if (index != -1) {
                this._mjNodeList.splice(index, 1);
            }
            this._newMj.destroy();
            this._newMj = null;
        }
    },

    getNewMj(n) {
        this.clearNewMj();
        this._newMj = cc.instantiate(this.mjprefab);
        let reslogic = this._newMj.getComponent('MJRes');
        reslogic.dir = this._dir;
        reslogic.onlyid = 13;
		if (this._dir == 0) {
			reslogic.isStand = true;
		}
		else {
			reslogic.isStand = false;
			reslogic.isShow = true;
		}

        this._newMj.x = this._newX;
        this._newMj.y = this._newY;
        this._newMj.zIndex = (320 - this._newMj.y);
        this._newMj.parent = this.node;

        if (this._dir == 0) {
            if (n != 0) {
                this.setMjPoint(this._newMj, n);
            }
			this._newMj.setScale((83+5)/83, (125+7.5)/125);
        }
		else {
			if (n != 0) {
				this.setMjPoint(this._newMj, n);
			}
		}
        this._mjNodeList.push(this._newMj);
    },

    clearLastOutMj() {
        this.clearOutMj(this._outList.length - 1);
    },

    clearOutMj(index) {
        if (this._outList[index] == null) {
            return;
        }
        this._outList[index].destroy();
        delete this._outList[index];
        this._outList.splice(index, 1);
    },

	getLastOutMjFlag () {
		let lastNode = null;
		if (this.outList && this.outList.length > 0) {
			lastNode = this._outList[this._outList.length-1]
		}
		if (!lastNode) {
			return null;
		}
		else {
            let reslogic = lastNode.getComponent('MJRes');
			return reslogic.flaglast;
		}
	},

    clearOutMjFlag() {
        for (let i = 0; i < this._outList.length; i++) {
            const mj = this._outList[i];
            let reslogic = mj.getComponent('MJRes');
            if (reslogic.flaglast) {
                reslogic.flaglast = false;
            }
        }
    },

    addOutMj(n, flag = true) {
        if (n == 0) { return; }
        let outmj = cc.instantiate(this.mjprefab);
        let reslogic = outmj.getComponent('MJRes');
        reslogic.dir = this._dir;
        reslogic.majiang = n;
        reslogic.isStand = false;
        reslogic.isShow = true;
        reslogic.flaglast = flag;

        let i = this._outList.length;
        let l = Math.floor(i / this._outLineNum);
        let x = this._outBeginX + (i % this._outLineNum) * this._outIntervalX;
        let y = this._outBeginY + this._outIntervalY * l;
        /* if (l > 1) {
            x = this._outBeginX + this._outLineNum * this._outIntervalX;
            y = this._outBeginY + this._outIntervalY * (l - 1);
        } */
        if (this._dir == 1 || this._dir == 3) {
            x = this._outBeginX + this._outIntervalX * Math.floor(i / this._outLineNum);
            y = this._outBeginY + (i % this._outLineNum) * this._outIntervalY;
        }
		if (this._dir == 0) {
			outmj.setContentSize(40, 61);
		}
        outmj.x = x;
        outmj.y = y;
        outmj.zIndex = (320 - outmj.y);
        outmj.parent = this.node;
        this._outList.push(outmj);
    },

    clearOperMjList() {
        for (let i = 0; i < this._operList.length; i++) {
            let item = this._operList[i];
            let list = item.nodelist || [];
            for (let n = 0; n < list.length; n++) {
                let node = list[n];
                node.destroy();
            }
        }
        this._operList = [];
    },

    makeMj(n, show = false) {
        let mj = cc.instantiate(this.mjprefab);
        let reslogic = mj.getComponent('MJRes');
        reslogic.dir = this._dir;
        reslogic.majiang = n;
        reslogic.isStand = false;
        reslogic.isShow = show;
        return mj
    },

    addOperMj(mjlist, mjtype = 'pt', operpos = 1, needact = true) {
        let beginx = 0;
        let beginy = 0;
        mjlist.sort();
        let nodelist = [];

        for (let i = 0; i < mjlist.length; i++) {
            let fix_zorder_y = 0;
            let point = mjlist[i];
            let isshow = false;
            if ('peng' == mjtype || ('angang' == mjtype && i == 3) || 'pinggang' == mjtype) {
                isshow = true;
            }
            let mj = this.makeMj(point, isshow);
            let x = 0;
            let y = 0;
            if (this._dir == 0 || this._dir == 2) {
				let _outIntervalX = (this._dir == 0)? 63:this._outIntervalX; /* don't touch */ 
                let beginx = this._operationX + this._operList.length * (_outIntervalX * 3 + this._operationIntervalX);
                x = beginx + i * _outIntervalX;
                y = this._operationY;
                if (('angang' == mjtype || 'pinggang' == mjtype) && i == 3) {
                    x = beginx + operpos * _outIntervalX;
                    y = this._operationY + this._operationIntervalY;
                    fix_zorder_y = 100;
                }
            }
            if (this._dir == 1 || this._dir == 3) {
                x = this._operationX;
                let beginy = this._operList.length * (this._operationIntervalY * 3 + this._operationIntervalX);
                y = this._operationY + beginy + i * this._outIntervalY;
                /* if (mjtype == 'angang') {
                    y = this._operationY + beginy + i % 2 * this._outIntervalY + this._operationIntervalY2 * Math.floor(i / 2);
                    fix_zorder_y = Math.floor(i / 2) > 0 ? 100 : 0;
                } */
                if (('angang' == mjtype || 'pinggang' == mjtype) && i == 3) {
                    let node = nodelist[operpos];
                    y = node.y + this._operationIntervalY2;
                    fix_zorder_y = 100;
                }
            }
            mj.parent = this.node;
            mj.x = x;
            mj.y = y;
            mj.zIndex = (320 - mj.y + fix_zorder_y);
			if (this._dir == 0) {
				mj.setScale(63/53); 
			}
            nodelist.push(mj);
        }
        let operitem = {
            type: mjtype,
            mjlist: mjlist,
            nodelist: nodelist,
        }
        this._operList.push(operitem);
        if (needact) {
            this.playOperAct(mjtype);
        }
    },

    playOperAct(mjtype) {
        if ('chi' == mjtype) {
            this.OperAct.play(0);
        } else if ('peng' == mjtype) {
            this.OperAct.play(1);
        } else if ('angang' == mjtype || 'pinggang' == mjtype || 'wangang' == mjtype) {
            this.OperAct.play(2);
        } else if ('hu' == mjtype) {
            this.OperAct.play(3);
        } else if ('zimo' == mjtype) {
            this.OperAct.play(4);
        }
    },


    clearAllOutMj() {
        for (let i = this._outList.length - 1; i >= 0; i--) {
            this.clearOutMj(i);
        }
    },

    testOutList(n) {
        this.clearAllOutMj();
        this._outList = [];
        for (let i = 0; i < n; i++) {
            this.addOutMj(36);
        }
    },

    outList(list, islastout = false) {
        this.clearAllOutMj();
        let flag = false;
        for (let i = 0; i < list.length; i++) {
            const mj = list[i];
            if (i == list.length - 1 && islastout) {
                flag = true;
            } 
            this.addOutMj(mj, flag);
        }
    },

	showTing: function (list, qidui) {
		let canHu = MJLogic.canHu(list, 35, qidui);
		if (this.tingNode) {
			if (this._dir == 0 && canHu) {
				this.tingNode.active = true;
				this.tingNode.zIndex = 999;
				let Layout = cc.find('Layout', this.tingNode);
				for (let node of Layout.children) {
					node.destroy();
				}
				let item = cc.find('Item', this.tingNode);
				let canWinCards = MJLogic.getCanWinCards(list, qidui);
				for (let card of canWinCards) {
					let node = cc.instantiate(item);
					node.active = true;
					node.y = 0;
					node.parent = Layout;
					// let str = 'User_' + ((card <= 9)? '0'+card:''+card);
					let str = "down_"+Math.floor(card/10)+"_"+(card%10);
					node.getComponent(cc.Sprite).spriteFrame = this.mjAtlas.getSpriteFrame(str);
				}
				let bg = cc.find('bg', this.tingNode);
				this.scheduleOnce(() => {
					bg.width = Layout.width+50;
				}, 0);

			}
			else {
				this.tingNode.active = false;
			}
		}
	},
});

